<template>
  <view class="attendance-container">
    <!-- Header -->
    <view class="header" :style="currentGradient">
      <text class="title">授课打卡</text>
    </view>

    <!-- Course Selection -->
    <view class="section card" v-if="clockOutSessions.length === 0">
      <view class="section-header">
        <text>选择课程</text>
      </view>
      <picker
        mode="selector"
        :range="courseOptions"
        range-key="name"
        @change="onCourseChange"
      >
        <view class="picker">
          <text>{{ selectedCourse?.name || "请选择课程" }}</text>
          <uni-icons type="arrowdown" size="16" color="#666"></uni-icons>
        </view>
      </picker>
    </view>

    <!-- Class Selection (only shows when course selected) -->
    <view
      class="section card"
      v-if="selectedCourse && clockOutSessions.length === 0"
    >
      <view class="section-header">
        <text>选择班级</text>
      </view>
      <picker
        mode="selector"
        :range="filteredClassOptions"
        range-key="name"
        @change="onClassChange"
      >
        <view class="picker">
          <text>{{ selectedClass?.name || "请选择班级" }}</text>
          <uni-icons type="arrowdown" size="16" color="#666"></uni-icons>
        </view>
      </picker>
    </view>

    <!-- Students List (only shows when class selected) -->
    <view
      class="section card"
      v-if="selectedClass && clockOutSessions.length === 0"
    >
      <view class="section-header">
        <text>选择学员</text>
        <button size="mini" @click="toggleSelectAll" class="select-all-btn">
          {{ selectAllText }}
        </button>
      </view>
      <scroll-view scroll-y class="students-list">
        <view
          class="student-item"
          v-for="student in classStudents"
          :key="student.id"
          @click="toggleSelect(student)"
        >
          <view class="student-info">
            <image
              :src="student.avatar || '/static/images/avatar-default.png'"
              class="avatar"
            />
            <text>{{ student.name }}</text>
          </view>
          <checkbox :checked="selectedStudents.includes(student.id)"></checkbox>
        </view>
      </scroll-view>
    </view>

    <!-- Clock Out Sessions List (从后台获取) -->
    <view class="section card" v-if="clockOutSessions.length > 0">
      <view class="section-header">
        <text>待下课课程</text>
        <button
          size="mini"
          @click="refreshClockOutSessions"
          class="refresh-btn"
        >
          刷新
        </button>
      </view>
      <scroll-view scroll-y class="sessions-list">
        <view
          class="session-item"
          v-for="session in clockOutSessions"
          :key="session.classId"
          @click="selectClockOutSession(session)"
          :class="{
            selected: selectedClockOutSession?.classId === session.classId,
          }"
        >
          <view class="session-info">
            <text>{{ session.className }}</text>
            <text class="session-time">{{
              formatSessionTime(session.startTime)
            }}</text>
          </view>
          <view class="session-students">
            <text>开始时间: {{ session.startTime }}</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- Action Buttons -->
    <view class="action-buttons">
      <button
        class="check-in-btn"
        :disabled="!canCheckIn || clockOutSessions.length > 0"
        :class="[
          'check-in-btn',
          { 'btn-disabled': !canCheckIn || clockOutSessions.length > 0 },
        ]"
        @click="handleCheckIn"
        v-if="clockOutSessions.length === 0"
        :style="
          canCheckIn && clockOutSessions.length === 0 ? currentGradient : ''
        "
      >
        <uni-icons type="circle-filled" size="18" color="#fff"></uni-icons>
        <text>上课打卡</text>
      </button>
      <button
        class="check-out-btn"
        :disabled="!canCheckOut || !selectedClockOutSession"
        :class="[
          'check-out-btn',
          { 'btn-disabled': !canCheckOut || !selectedClockOutSession },
        ]"
        @click="handleCheckOut"
        v-if="clockOutSessions.length > 0"
        :style="canCheckOut && selectedClockOutSession ? currentGradient : ''"
      >
        <uni-icons type="circle-filled" size="18" color="#fff"></uni-icons>
        <text>下课打卡</text>
      </button>
    </view>

    <!-- Status Indicator -->
    <view class="status-indicator" v-if="currentStatus">
      <text :class="statusClass" :style="{ color: currentTheme.primary }">{{
        currentStatus
      }}</text>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import {
  getCourseOptions,
  getTeacherClassTree,
  clockIn,
  getClockOutListByTeacherId,
  clockOut,
} from "@/api/attendanceApi";
import { getCurrentTheme } from "@/utils/theme";

// State Management
const courseOptions = ref([]);
const selectedCourse = ref(null);
const selectedClass = ref(null);
const selectedStudents = ref([]);
const activeSession = ref(null);
const currentStatus = ref("");

// 新增状态
const clockOutSessions = ref([]); // 存储所有待下课的课程
const selectedClockOutSession = ref(null); // 用户选择的待下课课程

// 从API获取的班级和学生数据
const classOptions = ref([]);
const allStudents = ref([]);

// 获取当前主题
const currentTheme = computed(() => getCurrentTheme());

// 计算当前主题的渐变样式
const currentGradient = computed(() => {
  return `background: linear-gradient(135deg, ${currentTheme.value.start} 0%, ${currentTheme.value.end} 100%);`;
});

// Computed Properties
const filteredClassOptions = computed(() => {
  return selectedCourse.value
    ? classOptions.value.filter((c) => c.courseId === selectedCourse.value.id)
    : [];
});

const classStudents = computed(() => {
  return selectedClass.value
    ? allStudents.value.filter((s) => s.classId === selectedClass.value.id)
    : [];
});

const canCheckIn = computed(() => {
  return (
    selectedClass.value &&
    selectedStudents.value.length > 0 &&
    !activeSession.value
  );
});

const canCheckOut = computed(() => {
  return clockOutSessions.value && clockOutSessions.value.length > 0;
});

const statusClass = computed(() => {
  return activeSession.value ? "status-active" : "status-completed";
});

const selectAllText = computed(() => {
  return selectedStudents.value.length === classStudents.value.length
    ? "取消全选"
    : "全选";
});

// Methods
const onCourseChange = (e) => {
  selectedCourse.value = courseOptions.value[e.detail.value];
  const userInfo = uni.getStorageSync("userInfo");
  const teacherId = userInfo?.id || userInfo?.userId || 0;

  // 调用API获取班级和学生数据
  getTeacherClassTree(teacherId, selectedCourse.value.id).then((res) => {
    if (res.data && res.data.classInfo) {
      // 转换班级数据格式
      classOptions.value = res.data.classInfo.map((cls) => ({
        id: cls.id,
        courseId: selectedCourse.value.id,
        name: cls.className,
      }));

      // 转换学生数据格式
      const students = [];
      res.data.classInfo.forEach((cls) => {
        if (cls.studentInfo && Array.isArray(cls.studentInfo)) {
          cls.studentInfo.forEach((student) => {
            students.push({
              id: student.value,
              classId: cls.id,
              name: student.realName,
              avatar: "",
            });
          });
        }
      });

      // 更新学生数据
      allStudents.value = students;
    }
  });

  selectedClass.value = null;
  selectedStudents.value = [];
};

const onClassChange = (e) => {
  selectedClass.value = filteredClassOptions.value[e.detail.value];
  selectedStudents.value = [];
};

const toggleSelect = (student) => {
  const index = selectedStudents.value.indexOf(student.id);
  if (index > -1) {
    selectedStudents.value.splice(index, 1);
  } else {
    selectedStudents.value.push(student.id);
  }
};

const toggleSelectAll = () => {
  if (selectedStudents.value.length === classStudents.value.length) {
    selectedStudents.value = [];
  } else {
    selectedStudents.value = classStudents.value.map((s) => s.id);
  }
};

const handleCheckIn = () => {
  // 获取用户信息
  const userInfo = uni.getStorageSync("userInfo");
  const teacherId = userInfo?.id || userInfo?.userId || 0;

  // 构造打卡数据
  const clockInData = {
    classId: selectedClass.value.id,
    teacherId: teacherId,
    studentIds: [...selectedStudents.value],
  };

  // 调用打卡API
  clockIn(clockInData)
    .then((res) => {
      if (res.code === 200) {
        // API调用成功
        uni.showToast({ title: "上课打卡成功", icon: "success" });

        // 打卡成功后重新获取待下课的课程
        fetchClockOutSessions();
      } else {
        // API调用失败
        uni.showToast({ title: res.msg || "打卡失败", icon: "none" });
      }
    })
    .catch((err) => {
      // 网络错误或其他异常
      console.error("打卡失败:", err);
      uni.showToast({ title: "打卡失败，请重试", icon: "none" });
    });
};

const handleCheckOut = () => {
  if (!selectedClockOutSession.value) {
    uni.showToast({
      title: "请选择要结束的课程",
      icon: "none",
      duration: 2000,
    });
    return;
  }

  // 构造下课打卡数据 - 根据后台数据结构进行调整
  const clockOutData = {
    classId: selectedClockOutSession.value.classId,
  };

  // 调用下课打卡API
  clockOut(clockOutData)
    .then((res) => {
      if (res.code === 200) {
        uni.showToast({ title: "下课打卡成功", icon: "success" });

        // 打卡成功后回到初始化状态
        resetToInitialState();
      } else {
        uni.showToast({ title: res.msg || "下课打卡失败", icon: "none" });
      }
    })
    .catch((err) => {
      console.error("下课打卡失败:", err);
      uni.showToast({ title: "下课打卡失败，请重试", icon: "none" });
    });
};

// 重置到初始化状态
const resetToInitialState = () => {
  // 清空所有选择状态
  selectedCourse.value = null;
  selectedClass.value = null;
  selectedStudents.value = [];
  selectedClockOutSession.value = null;

  // 清空班级和学生数据
  classOptions.value = [];
  allStudents.value = [];

  // 重新获取待下课的课程列表
  fetchClockOutSessions();
};

const formatTime = (date) => {
  return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
};

const formatSessionTime = (dateString) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  return formatTime(date);
};

// 获取教师ID
const getTeacherId = () => {
  const userInfo = uni.getStorageSync("userInfo");
  return userInfo?.id || userInfo?.userId || 0;
};

// 获取待下课的课程
const fetchClockOutSessions = () => {
  const teacherId = getTeacherId();

  getClockOutListByTeacherId(teacherId)
    .then((res) => {
      if (res.code === 200) {
        // 使用 rows 字段获取数据列表，并根据实际字段进行映射
        console.log("获取待下课的课程:", res.rows);
        clockOutSessions.value = res.rows || [];
        selectedClockOutSession.value = null;
      } else {
        uni.showToast({ title: res.msg || "获取待下课课程失败", icon: "none" });
      }
    })
    .catch((err) => {
      console.error("获取待下课课程失败:", err);
      uni.showToast({ title: "获取待下课课程失败", icon: "none" });
    });
};

// 刷新待下课的课程
const refreshClockOutSessions = () => {
  fetchClockOutSessions();
};

// 选择待下课的课程
const selectClockOutSession = (session) => {
  selectedClockOutSession.value = session;
};

// Initialize
onMounted(() => {
  getCourseOptions().then((res) => {
    courseOptions.value = res.data.map((item) => ({
      id: item.dictValue,
      name: item.dictLabel,
    }));
  });

  // 获取待下课的课程
  fetchClockOutSessions();
});
</script>

<style scoped lang="scss">
.attendance-container {
  min-height: 100vh;
  padding: 20rpx;
  background-color: $background-color;
  display: flex;
  flex-direction: column;
}

.header {
  margin-bottom: 30rpx;
  text-align: center;
  border-radius: 12rpx;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 10rpx;

  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: white;
    padding: 30rpx 0;
  }
}

.section {
  background: white;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    font-size: 28rpx;
    font-weight: bold;
    color: #333;

    .select-all-btn,
    .refresh-btn {
      padding: 0 20rpx;
      height: 50rpx;
      line-height: 50rpx;
      background: #f0f0f0;
      border-radius: 25rpx;
      border: none;
      font-size: 24rpx;
    }
  }
}

.picker {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border: 1px solid #eee;
  border-radius: 8rpx;
}

.students-list,
.sessions-list {
  max-height: 500rpx;
}

.student-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #f5f5f5;

  .student-info {
    display: flex;
    align-items: center;

    .avatar {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      margin-right: 20rpx;
      background-color: #eee;
    }
  }
}

.session-item {
  padding: 20rpx;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;

  &.selected {
    background-color: #e8f5e9;
  }

  .session-info {
    display: flex;
    justify-content: space-between;
    font-weight: bold;
    margin-bottom: 10rpx;

    .session-time {
      color: #4caf50;
    }
  }

  .session-students {
    color: #666;
    font-size: 24rpx;
  }
}

.action-buttons {
  display: flex;
  gap: 20rpx;
  margin-top: 30rpx;

  button {
    flex: 1;
    height: 90rpx;
    border-radius: 12rpx;
    border: none;
    font-size: 32rpx;
    font-weight: bold;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10rpx;

    // 默认状态下的过渡效果
    transition: all 0.3s ease;
  }

  .check-in-btn {
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);

    &:active {
      transform: translateY(2px);
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
    }

    // 禁用状态
    &.btn-disabled,
    &[disabled] {
      background: #cccccc !important;
      box-shadow: none;
      opacity: 0.7;
      transform: none;
      color: rgba(255, 255, 255, 0.8);
    }
  }

  .check-out-btn {
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);

    &:active {
      transform: translateY(2px);
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
    }

    // 禁用状态
    &.btn-disabled,
    &[disabled] {
      background: #cccccc !important;
      box-shadow: none;
      opacity: 0.7;
      transform: none;
      color: rgba(255, 255, 255, 0.8);
    }
  }
}

.status-indicator {
  margin-top: 30rpx;
  text-align: center;
  font-size: 28rpx;

  .status-active {
    font-weight: bold;
  }

  .status-completed {
    font-weight: bold;
  }
}
</style>
